/* eslint-disable no-console */
// useWebRTC.ts
import { ref, onMounted, onUnmounted, watch } from 'vue'
import type { Ref } from 'vue'
import SimplePeer from 'simple-peer'

interface WebRTCOptions {
  url?: string
  autoPlay?: boolean
  iceServers?: RTCIceServer[]
  // 认证参数
  auth?: {
    appid?: string
    apikey?: string
    apisecret?: string
    sceneid?: string
    [key: string]: any
  }
}

interface WebRTCReturn {
  videoRef: Ref<HTMLVideoElement | null>
  status: Ref<string>
  isConnected: Ref<boolean>
  isPlaying: Ref<boolean>
  connect: (newUrl?: string, auth?: any) => void
  disconnect: () => void
  setUrl: (newUrl: string) => void
  setAuth: (auth: any) => void
}

export function useWebRTC(options: WebRTCOptions = {}): WebRTCReturn {
  const {
    autoPlay = true,
    iceServers = [
      { urls: 'stun:stun.l.google.com:19302' },
      { urls: 'stun:stun1.l.google.com:19302' },
    ],
    auth: initialAuth = {},
  } = options

  const url = ref<string | undefined>(options.url)
  const auth = ref<any>(initialAuth)
  const videoRef = ref<HTMLVideoElement | null>(null)
  const status = ref<string>('初始化')
  const isConnected = ref<boolean>(false)
  const isPlaying = ref<boolean>(false)

  let peer: SimplePeer.Instance | null = null
  let signalSocket: WebSocket | null = null

  // 解析WebRTC URL
  const parseWebRTCUrl = (webrtcUrl: string) => {
    const urlObj = new URL(webrtcUrl.replace('webrtc://', 'https://'))
    return {
      host: urlObj.hostname,
      port: urlObj.port || '9850',
      app: urlObj.pathname.split('/')[1], // 通常是 'live'
      streamId: urlObj.pathname.split('/')[2], // 流ID
      schema: urlObj.searchParams.get('schema') || 'https',
    }
  }

  // 设置新URL
  const setUrl = (newUrl: string) => {
    url.value = newUrl
  }

  // 设置认证信息
  const setAuth = (newAuth: any) => {
    auth.value = newAuth
  }

  // 建立WebRTC连接
  const connect = (newUrl?: string, newAuth?: any) => {
    // 如果提供了新URL，则更新
    if (newUrl) {
      url.value = newUrl
    }

    // 如果提供了新认证信息，则更新
    if (newAuth) {
      auth.value = newAuth
    }

    // 检查URL是否存在
    if (!url.value) {
      status.value = 'URL未设置'
      return
    }

    if (!videoRef.value) {
      status.value = '视频元素未就绪'
      return
    }

    // 清理之前的连接
    disconnect()

    try {
      const { host, port, app, streamId, schema } = parseWebRTCUrl(url.value)

      // 构建信令服务器URL - 使用流URL的主机和端口
      const wsProtocol = schema === 'https' ? 'wss' : 'ws'
      const wsUrl = `${wsProtocol}://${host}:${port}/rtc/v1/play/`

      status.value = '正在连接信令服务器...'
      console.log('正在连接信令服务器:', wsUrl)
      console.log('流地址:', url.value)
      console.log('认证信息:', auth.value)

      signalSocket = new WebSocket(wsUrl)

      signalSocket.onopen = () => {
        status.value = '信令服务器已连接，正在请求流...'
        console.log('信令服务器已连接')

        // 构建包含认证信息的请求消息
        const offerMessage = {
          // 基本流信息
          streamurl: `${app}/${streamId}`,
          sdp: '',
          audio: true,
          video: true,

          // 添加认证信息
          ...auth.value,
        }

        console.log('发送信令消息:', offerMessage)
        signalSocket?.send(JSON.stringify(offerMessage))
      }

      signalSocket.onmessage = (event) => {
        try {
          console.log('收到信令消息:', event.data)
          const message = JSON.parse(event.data)

          if (message.sdp) {
            status.value = '收到SDP，建立WebRTC连接...'

            // 创建WebRTC对等连接
            peer = new SimplePeer({
              initiator: true,
              trickle: false,
              config: {
                iceServers,
              },
            })

            // 处理WebRTC事件
            peer.on('signal', (data) => {
              // 发送我们的信令数据到服务器
              const answerMessage = {
                streamurl: `${app}/${streamId}`,
                sdp: JSON.stringify(data),
                audio: true,
                video: true,
                // 添加认证信息
                ...auth.value,
              }

              if (signalSocket && signalSocket.readyState === WebSocket.OPEN) {
                console.log('发送应答信令:', answerMessage)
                signalSocket.send(JSON.stringify(answerMessage))
              }
            })

            peer.on('connect', () => {
              status.value = '已连接'
              isConnected.value = true
              console.log('WebRTC已连接')
            })

            peer.on('stream', (stream) => {
              if (videoRef.value) {
                videoRef.value.srcObject = stream
                status.value = '正在播放'
                isPlaying.value = true
                console.log('接收到媒体流，开始播放')
              }
            })

            peer.on('error', (err) => {
              status.value = `错误: ${err.message}`
              isConnected.value = false
              isPlaying.value = false
              console.error('WebRTC错误:', err)
            })

            // 处理来自服务器的SDP
            console.log('处理服务器SDP:', message.sdp)
            peer.signal(JSON.parse(message.sdp))
          }

          if (message.candidate) {
            // 处理ICE候选
            console.log('收到ICE候选:', message.candidate)
            if (peer) {
              peer.signal({ candidate: message.candidate })
            }
          }

          // 处理可能的错误消息
          if (message.error) {
            status.value = `服务器错误: ${message.error}`
            console.error('服务器返回错误:', message.error)
          }
        } catch (error) {
          console.error('处理信令消息错误:', error)
          status.value = '信令处理错误'
        }
      }

      signalSocket.onerror = (error) => {
        console.error('信令WebSocket错误:', error)
        status.value = '信令连接错误'
        isConnected.value = false
      }

      signalSocket.onclose = (event) => {
        console.log('信令WebSocket关闭:', {
          code: event.code,
          reason: event.reason,
          wasClean: event.wasClean,
        })
        status.value = `信令连接已关闭: ${event.code} ${event.reason || ''}`
        isConnected.value = false
      }
    } catch (error) {
      console.error('建立WebRTC连接错误:', error)
      status.value = '连接错误'
    }
  }

  // 断开连接
  const disconnect = () => {
    isConnected.value = false
    isPlaying.value = false

    if (peer) {
      peer.destroy()
      peer = null
    }

    if (signalSocket) {
      signalSocket.close()
      signalSocket = null
    }

    if (videoRef.value && videoRef.value.srcObject) {
      const tracks = (videoRef.value.srcObject as MediaStream).getTracks()
      tracks.forEach((track) => track.stop())
      videoRef.value.srcObject = null
    }

    status.value = '已断开'
  }

  // 监听URL变化
  watch(url, (newUrl) => {
    if (newUrl && isConnected.value) {
      // 如果URL变化且当前已连接，则重新连接
      connect(newUrl)
    }
  })

  // 监听认证信息变化
  watch(
    auth,
    (newAuth) => {
      if (url.value && isConnected.value) {
        // 如果认证信息变化且当前已连接，则重新连接
        connect(undefined, newAuth)
      }
    },
    { deep: true },
  )

  onMounted(() => {
    if (autoPlay && url.value) {
      connect()
    }
  })

  onUnmounted(() => {
    disconnect()
  })

  return {
    videoRef,
    status,
    isConnected,
    isPlaying,
    connect,
    disconnect,
    setUrl,
    setAuth,
  }
}
